All files / src/app/api/admin/categories/[id] route.ts

95.48% Statements 127/133
65% Branches 13/20
100% Functions 3/3
95.48% Lines 127/133

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 1341x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 6x 6x 6x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x     3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x  
export const dynamic = "force-dynamic";
 
import { NextRequest, NextResponse } from 'next/server';
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  noContentResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
import { prisma } from "@/lib/prisma";
import { z } from "zod";
import { invalidatePattern } from "@/lib/core";
 
// Validation schema for updating a category
const updateCategorySchema = z.object({
  title: z.string().min(1, "Title is required"),
  slug: z.string().min(1, "Slug is required"),
  imageUrl: z.string().url().optional().nullable(),
  description: z.string().optional().nullable(),
  parentId: z
    .union([z.string(), z.number()])
    .transform((val) => (typeof val === "string" ? parseInt(val) : val))
    .optional()
    .nullable() });
 
type Category = {
  id: number;
  title: string;
  slug: string;
  imageUrl: string | null;
  description: string | null;
  parentId: number | null;
  children?: unknown[];
  _count?: { products: number };
};
 
/**
 * GET /api/admin/categories/[id]
 * Get single category
 * Public endpoint - no authentication required
 */
async function handleGet(
  request: NextRequest,
  context: RouteContext | undefined
): Promise<NextResponse<ApiSuccessResponse<Category> | ApiErrorResponse>> {
  if (!context?.params) {
    throw ApiError.invalidId("category");
  }
  const resolvedParams = await context.params;
  const id = parseInt(resolvedParams.id);
 
  const category = await prisma.category.findUnique({
    where: { id },
    include: {
      children: true,
      _count: { select: { products: true } } } });
 
  if (!category) {
    throw ApiError.notFound("Category");
  }
 
  return successResponse(category);
}
 
/**
 * PUT /api/admin/categories/[id]
 * Update category
 * Admin only endpoint
 */
async function handlePut(
  request: NextRequest,
  context: RouteContext | undefined
): Promise<NextResponse<ApiSuccessResponse<Category> | ApiErrorResponse>> {
  if (!context?.params) {
    throw ApiError.invalidId("category");
  }
  const resolvedParams = await context.params;
  const id = parseInt(resolvedParams.id);
  const body = await request.json();
 
  // Validate request body
  const validation = updateCategorySchema.safeParse(body);
  if (!validation.success) {
    throw ApiError.validation("Validation failed", validation.error.flatten().fieldErrors);
  }
 
  const { title, slug, imageUrl, description, parentId } = validation.data;
 
  const category = await prisma.category.update({
    where: { id },
    data: {
      title,
      slug,
      imageUrl: imageUrl || null,
      description: description || null,
      parentId: parentId || null } });
 
  // Invalidate all categories cache entries
  await invalidatePattern("categories:*");
 
  return successResponse(category);
}
 
/**
 * DELETE /api/admin/categories/[id]
 * Delete category
 * Admin only endpoint
 */
async function handleDelete(
  request: NextRequest,
  context: RouteContext | undefined
): Promise<NextResponse> {
  if (!context?.params) {
    throw ApiError.invalidId("category");
  }
  const resolvedParams = await context.params;
  const id = parseInt(resolvedParams.id);
 
  await prisma.category.delete({
    where: { id } });
 
  // Invalidate all categories cache entries
  await invalidatePattern("categories:*");
 
  return noContentResponse();
}
 
export const GET = withErrorHandling(handleGet);
export const PUT = withErrorHandling(withAdmin(handlePut));
export const DELETE = withErrorHandling(withAdmin(handleDelete));